import axios from './http.js'
import { Session } from '../../packages/index';
import qs from 'qs'
// 获取所有题目
export async function getList(url, params = null, useCache = true) {
  const cacheKey = getFormatFullUrl(url, params)  // getCacheKeyByUrlAndParam(urlSet, params);
  const dataFromCache = Session.get(cacheKey);
  let listData = null
  if (useCache && dataFromCache) { //如果确定使用缓存
    listData = dataFromCache.listData
  }
  let hasData = false
  if (!listData) {//缓存中没有，则去服务器
    if (!params) {
      params = {}
    }

    const result = await axios.get(url, {
      params, paramsSerializer: {
        serialize: params => {
          return qs.stringify(params, { indices: false })
        }
      }
    })
    //  await request.get<T>(urlSet.apiUrl,
    //     { params }
    // );
    // listData = { list: result.data, totalCount: result.totalCount }
    const resultData = result.data
    let totalCount = 0
    if (resultData) {
      if (resultData.listData) {
        listData = resultData.listData
        totalCount = resultData.totalCount
      } else {
        listData = resultData
        totalCount = listData.length
      }

    }


    hasData = listData && listData.length > 0
    if (useCache && hasData) {//拥有数据的，才进行缓存,

      Session.set(cacheKey, { listData, totalCount });
    }
  } else {
    hasData = listData && listData.length > 0
  }

  if (hasData && params && params.searchText && params.searchFieldNames) {
    const searchFields = params.searchFieldNames
    const sText = params.searchText
    const filterData = listData.filter((dataItem) => {  //list.
      let r = false
      for (let i = 0; i < searchFields.length; i++) {
        const fname = searchFields[i]
        if (dataItem[fname] && dataItem[fname].toString().indexOf(sText) != -1) {
          r = true;
        }
      }
      return r;
    })

    listData = filterData // .list= { list: filterData, totalCount: dataFromCache.totalCount }
  }

  return listData

}


export function getFormatFullUrl(url, data) {
  let params = ``;
  for (let key in data) {
    if (data[key] != null && data[key] != '') {
      if (params.length == 0) {
        params += `?${key}=${data[key]}`;
      } else {
        params += `&${key}=${data[key]}`;
      }
    }
  }
  url += params;
  return url;
}

// 发送验证码
export function sendVaildCode(data) {
  return axios({
    url: '/api/user/sendValidCode',
    method: 'post',
    data
  })
}

// 验证验证码是否正确
export function checkVaildCode(data) {
  return axios({
    url: '/api/user/checkValidCode',
    method: 'post',
    data
  })
}
// 获取所有科目
export async function getSubjectList(data) {

  return await getList('/q_api/subject/list', data)
}
// 获取所有题目
export async function getQuestionList(data) {
  return await getList('/q_api/question/list', data)
}

//获取对应题目的数据
export async function getQuestion(qid) {
  return await getList(`/q_api/question/${qid}`)//这个不应该是getList啊、。。
}
// 获取题组内的所有题目，应该是根据刷题数获取！！
export async function getQuestionGroupAllSub(gid, qidArray) {
  const params = { gid, qidArray }
  let useCache = false //默认不用缓存！！
  if (qidArray && qidArray.length) {
    useCache = true
  }
  return await getList('/q_api/questiongroup/getallquestions', params, useCache)
}


// 创建做题任务
export function createJob(data) {
  return axios({
    url: '/q_api/job/createjob',
    method: "post",
    data
  })
}

// 修改做题任务
export function updateJob(data) {
  return axios({
    url: '/q_api/job/updatejob',
    method: "post",
    data
  })
}

// 获取做题任务
export function getJob(data) {
  return axios({
    url: `/q_api/job/${data.session_id}`,
    method: 'get'
  })
}

// 获取做题任务
export async function getJobList(params, useCache = false) {
  // return axios({
  //   url: `/q_api/job/list`,
  //   method: 'get',
  //   params
  // })

  return await getList(`/q_api/job/list`, params, useCache)
}

export function sendmailList(data) {
  return axios({
    url: `/api/user/batchsendmail`,
    method: 'post',
    data
  })
}
export function resetVoteItemList(data) {
  return axios({
    url: `/api/voteitem/resetlist`,
    method: 'post',
    data
  })
}

export function setTutorByRandom(data) {
  return axios({
    url: `/api/choose/setrandomtutor`,
    method: 'post',
    data
  })

}
export function calCurrScores(data) {
  return axios({
    url: `/api/choose/calscores`,
    method: 'post',
    data
  })

}
export function calCurrFeedback(data) {
  return axios({
    url: `/api/choose/calfeedbacks`,
    method: 'post',
    data
  })

}
export function updategroup(data) {
  return axios({
    url: `/api/choose/updategroup`,
    method: 'post',
    data
  })
}
//可否不用这个
export function updatemembergrade(data) {
  return axios({
    url: `/api/studygroup/update`,
    method: 'post',
    data
  })
}
export function clearCache(url, params) {
  const cacheKey = getFormatFullUrl(url, params)  // getCacheKeyByUrlAndParam(urlSet, params);
  Session.remove(cacheKey)
}


export function removeCacheWithPrefix(url, params) {
  const prefix = getFormatFullUrl(url, params) 
  for (let i = sessionStorage.length - 1; i >= 0; i--) {
    const key = sessionStorage.key(i);
    if (key.startsWith(prefix)) {
      Session.remove(key);
    }
  }
}
export function resetStudyGroupCache(currNo) {
  const url = `/api/studygroup/list`
  const cacheKey = getFormatFullUrl(url, { currNo })
  Session.remove(cacheKey)

}

export function resetVoteItemListCache(voteID) {
  const url = `/api/voteitem/list`
  const cacheKey = getFormatFullUrl(url, { voteID })
  Session.remove(cacheKey)

}
export function resetJobListCache(gid) {
  const url = `/q_api/job/list`
  const url2 = '/q_api/job/rankinglist'
  const cacheKey = getFormatFullUrl(url, { gid })
  const cacheKey2 = getFormatFullUrl(url2, { gid })

  Session.remove(cacheKey)
  Session.remove(cacheKey2)
}
// 获取做题任务
export function resetJobList(data) {
  return axios({
    url: `/q_api/job/resetjoblist`,
    method: 'post',
    data
  })
}

export function recaljobmarks(data) {
  return axios({
    url: `/q_api/job/recaljobs`,
    method: 'post',
    data
  })
}
// 获取做题任务
export async function getRankingJobList(params) {
  // return axios({
  //   url: `/q_api/job/rankinglist`,
  //   method: 'get',
  //   params
  // })
  return await getList(`/q_api/job/rankinglist`, params)
}

export async function getIP() {
  return await axios({
    url: 'http://pv.sohu.com/cityjson?ie=utf-8', headers: {
      "Content-Type": "application/octet-stream",
      "Access-Control-Allow-Origin": "*",
    }
  })
}
// 更新学员学习数据,这里只是学生更新学习数据！！
export function getChooseUpdate(data) {
  return axios({
    url: `/api/choose/updatetaskresult`,
    method: 'post',
    data
  })
}

// 导入题目
export function importQuestion(data) {
  return axios({
    url: '/q_api/question/importquestions',
    method: 'post',
    data
  })
}
export function fixQuestions() {
  return axios({
    url: '/q_api/question/fixoldimport',
    method: 'post'
  })
}
// 更新token
export function refreshToken(data) {
  return axios({
    url: '/api/user/refreshjwttoken',
    method: 'post',
    data
  })
}
export function reportError(data) {
  return axios({
    url: '/q_api/question/reportError',
    method: 'post',
    data
  })
}
export async function getClassList(data) {

  return await getList('/api/teacher/classlist', data)
}

export async function getJudgeResults(data) {

  return await getList('/api/voteitem/judgeresults', data)
}

export async function directDownload(fileUrl, fileName) {
  const directApi = "/f_api/download/direct";
  const url =
    directApi + "?fileUrl=" + fileUrl + "&fileName=" + fileName || "未命名文件";
  // console.time("直接下载", url);
  return await axios.get(url)
}

export function setVoteTaskMarks(data) {
  return axios({
    url: `/api/choose/setvotetaskmarks`,
    method: 'post',
    data
  })

}
export function resetMarks(data) {
  return axios({
    url: `/api/vote/resetmarks`,
    method: 'post',
    data
  })

}
export function delUnUsedUsers(data) {
  return axios({
    url: `/api/user/delbadusers`,
    method: 'post',
    data
  })

}
export function resetPwd(data) {
  return axios({
    url: `/api/user/resetpwd`,
    method: 'post',
    data
  })

}
export function syncCourseJson(data) {
  return axios({
    url: `/api/course/synccoursejson`,
    method: 'post',
    data
  })

}


export function addResultShow(data) {
  return axios({
    url: `/api/resultshow/create`,
    method: 'post',
    data
  })
}
// 修复刷题任务得分
export function fixQuestionTask(data) {
  return axios({
    url: '/api/choose/recalquestion',
    method: 'post',
    data
  })
}

export function zipFileAndGetPath(data) {
  return axios({
    url: '/f_api/utils/zipfiles',
    method: 'post',
    data
  })
}
export function setTaskResultsScore(data) {
  return axios({
    url: '/api/choose/marktaskresults',
    method: 'post',
    data
  })
}
export function gettaskresult(data) {
  return axios({
    url: '/api/queryresult/gettaskresult',
    method: 'get',
    params: data
  })
}